# -*- coding: utf-8 -*-
import MultipartPostHandler
import urllib2
import sys
import re
import urllib

class uploader:
    def __init__(self):
        # parent.Editor.Image.showPreview('20091013101442-981904434.jpg');
       self.picNamePat = re.compile(r"showPreview\(\'(.+?)\'\);")

    def upload(self, localFileName):

        params = {
                'formids': 'pic',
                'submitmode':'submit',
                'submitname':'',
                "pic" : open(localFileName, "rb"),
                }
        validatorURL = "http://wenwen.soso.com/z/UploadPicNew3,uploadPic.d"
        opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
        result = opener.open(validatorURL, params).read()
        # print "result:\n%s\n" % (result,) + "*" * 20
        lines = result.split('\n')
        remoteName = ''
        for line in lines:
            try:
                remoteName = self.picNamePat.search(line).group(1)
            except:
                pass

        if remoteName == '':
            print result
            raise Exception()

        fullPath = "http://pic.wenwen.soso.com/p/" + remoteName[:8] + "/" + remoteName

        return  fullPath


if __name__ == "__main__":
    if len(sys.argv[1:]) < 1:
        print "usage: %s file1 file2 file3 ......" % (sys.argv[0],)
        sys.exit()

    u = uploader()
    for arg in sys.argv[1:]:
        localFileName = arg
        resultUrl = ''
        try:
            resultUrl = u.upload(localFileName)
        except Exception, e:
            print e
        else:
            print "uploaded %s as %s" % (localFileName, resultUrl)
